﻿using Esint.JudicialAuction.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Esint.Common;
using Esint.JudicialAuction.Model.Common;
using Esint.Common.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI.HtmlControls;
using Esint.Common.Model;

namespace WebJudicialAuction.admin.bases
{
    public class AdminBasePage : Page
    {
        #region 声明变量和读取配置文件

        static readonly string config_CommonJsSourceUrl = CommonExtend.GetAppSetting("CommonJsSource");
        static readonly string config_CommonCssSourceUrl = CommonExtend.GetAppSetting("CommonCssSource");

        static readonly string config_UploadScriptUrl = CommonExtend.GetAppSetting("UploadJsSource");
        static readonly string config_UploadCssUrl = CommonExtend.GetAppSetting("UploadCssSource");

        static readonly string config_TreeScriptUrl = CommonExtend.GetAppSetting("TreeJsSource");
        static readonly string config_TreeCssUrl = CommonExtend.GetAppSetting("TreeCssSource");

        static readonly string jsRootUrl = "/js/admin/";
        static readonly string cssRootUrl = "/css/admin/";

        static string jsTemplete = "<script src=\"{0}\" type=\"text/javascript\" charset=\"utf-8\"></script>" + Environment.NewLine;
        static string cssTemplete = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />" + Environment.NewLine;

        static readonly string strLoginUrl = "login.aspx";
        static readonly string strFramePage = CommonExtend.GetAppSetting("FramePage");
        static readonly string str500Page = CommonExtend.GetAppSetting("Page502");

        #endregion

        private bool isValidPower = false;

        /// <summary>
        /// 是否验证用户权限
        /// </summary>
        protected bool IsValidPower { get => isValidPower; set => isValidPower = value; }

        /// <summary>
        /// 丢应的页面权限点id
        /// </summary>
        protected string PageId { get; set; }

        /// <summary>
        /// 当前登录用户
        /// </summary>
        protected ISysUser CurrentUser { get; set; }

        /// <summary>
        /// 当前用户id
        /// </summary>
        protected string CurrentUserId
        {
            get { return this.CurrentUser == null ? "00000000-0000-0000-0000-000000000000" : CurrentUser.UserId; }
        }

        /// <summary>
        /// 用户是否登录标识
        /// </summary>
        private bool isUserLogin = false;

        /// <summary>
        /// 用户是否登录标识
        /// </summary>
        public bool IsUserLogin
        {
            get { return isUserLogin; }
            set { isUserLogin = value; }
        }

        private bool ignoreUserLogin = false;

        /// <summary>
        /// 是否忽略用户登录状态
        /// </summary>
        public bool IgnoreUserLogin
        {
            get { return ignoreUserLogin; }
            set { ignoreUserLogin = value; }
        }

        private bool isLoadCommonSource = true;

        /// <summary>
        /// 页面是否加载公共资源
        /// </summary>
        public bool IsLoadCommonSource
        {
            get { return isLoadCommonSource; }
            set { isLoadCommonSource = value; }
        }

        private bool isLoadUploadSource = false;

        /// <summary>
        /// 是否加载上传脚本
        /// </summary>
        public bool IsLoadUploadSource
        {
            get { return isLoadUploadSource; }
            set { isLoadUploadSource = value; }
        }

        private bool isLoadTreeSource = false;

        /// <summary>
        /// 是否加载上传
        /// </summary>
        public bool IsLoadTreeSource
        {
            get { return isLoadTreeSource; }
            set { isLoadTreeSource = value; }
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="requestFunc"></param>
        /// <param name="areaCode"></param>
        protected virtual void PowerValid(string areaCode = null)
        {
            //if (CurrentUser != null)
            //{
            //    var powerList = CurrentUser.UserPowerList;

            //    var rootObj = areaCode.IsNullOrEmpty() ? powerList.Find(x => x.MenuId == this.PageId) : powerList.Find(x => x.MenuId == this.PageId && x.AreaCode == areaCode);
            //    if (rootObj == null)
            //    {
            //        throw new PowerValidException(Validator.NotHasPower);
            //    }
            //}
        }

        /// <summary>
        /// 请求合法性验证
        /// </summary>
        protected virtual void RequestLegalValid()
        {
            CurrentUser = null;
            if (Session[SessionKey.UserInfo] != null)
            {
                CurrentUser = Session[SessionKey.UserInfo] as ISysUser;
                IsUserLogin = true;
                if (isValidPower)
                {
                    PowerValid();
                }
            }
            else
            {
                IsUserLogin = false;
                if (!IgnoreUserLogin)
                {
                    throw new NotLoginException("需要先登陆");
                }
            }
        }

        #region 加载公共资源相关方法

        /// <summary>
        /// 在页面上创建一个JS引用块
        /// </summary>
        /// <param name="jsUrl"></param>
        /// <returns></returns>
        protected virtual void LoadScriptToPage(string jsConfigValue)
        {
            if (string.IsNullOrWhiteSpace(jsConfigValue)) { return; }

            string[] jsSourceArr = jsConfigValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (jsSourceArr != null && jsSourceArr.Length > 0)
            {
                for (int i = 0; i < jsSourceArr.Length; i++)
                {
                    HtmlGenericControl jsControl = new HtmlGenericControl("script");
                    jsControl.Attributes["type"] = "text/javascript";
                    jsControl.Attributes["src"] = jsSourceArr[i];
                    this.Header.Controls.Add(jsControl);
                }
            }
        }

        /// <summary>
        /// 在页面上创建一个CSS引用块
        /// </summary>
        /// <param name="cssUrl"></param>
        /// <returns></returns>
        protected virtual void LoadStyleToPage(string cssConfigValue)
        {
            if (string.IsNullOrWhiteSpace(cssConfigValue)) { return; }

            string[] cssSourceArr = cssConfigValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (cssSourceArr != null && cssSourceArr.Length > 0)
            {
                for (int i = 0; i < cssSourceArr.Length; i++)
                {
                    HtmlGenericControl cssControl = new HtmlGenericControl("link");
                    cssControl.Attributes["rel"] = "stylesheet";
                    cssControl.Attributes["type"] = "text/css";
                    cssControl.Attributes["href"] = cssSourceArr[i];
                    this.Header.Controls.Add(cssControl);
                }
            }
        }

        protected virtual void LoadPageSources()
        {
            try
            {
                #region 加载公共资源

                if (IsLoadCommonSource)
                {
                    //加载样式公共资源
                    LoadStyleToPage(config_CommonCssSourceUrl);
                    //加载脚本公共资源
                    LoadScriptToPage(config_CommonJsSourceUrl);
                }

                #endregion

                #region 判断是否加载上传脚本和样式

                if (isLoadUploadSource)//判断是否加载上传脚本
                {
                    //加载上传样式
                    LoadStyleToPage(config_UploadCssUrl);
                    //加载上传脚本
                    LoadScriptToPage(config_UploadScriptUrl);

                    HtmlGenericControl uploadContainer = new HtmlGenericControl("div");
                    uploadContainer.InnerHtml = "<div id=\"file_container\" class=\"noshow\"></div><div id=\"file_Block\"><ul class=\"upload-img\"></ul><ul class=\"upload-list\"></ul></div>";
                    this.Form.Controls.Add(uploadContainer);
                }

                #endregion

                #region 判断是否加载树资源

                if (isLoadTreeSource)
                {
                    //加载树样式
                    LoadStyleToPage(config_TreeCssUrl);
                    //加载树脚本
                    LoadScriptToPage(config_TreeScriptUrl);
                    
                }

                #endregion

                #region 加载本页面资源

                var pageName = GetPhysicalFileNameWithoutExt();
                var pageJsPath = jsRootUrl + $"{pageName}.js";
                var pageCssPath = cssRootUrl + $"{pageName}.css";

                var phyPageJsPath = Server.MapPath(pageJsPath);
                var phyPageCssPath = Server.MapPath(pageCssPath);

                if (File.Exists(phyPageCssPath))
                {
                    //加载本页专属CSS
                    LoadStyleToPage(pageCssPath);
                }

                if (File.Exists(phyPageJsPath))
                {
                    //加载本页专属JS
                    LoadScriptToPage(pageJsPath);
                }
                
                #endregion
            }
            catch (Exception ex)
            {
                CommonExtend.ErrorLog(ex, "LoadPageSources异常");
                Response.Redirect(str500Page, true);
            }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            #region 自定义逻辑
            try
            {

                #region 验证请求合法性

                RequestLegalValid();

                #endregion

                #region 加载资源

                LoadPageSources();

                #endregion

                #endregion
            }
            catch (NotLoginException loginEx)
            {
                Response.Redirect(strLoginUrl, true);
            }
            catch (PowerValidException powerEx)
            {
                CommonExtend.ErrorLog(powerEx, "权限验证异常");
                Response.Write("您没有权限访问此页面");
                Response.End();
            }
            catch (DataValidException validEx)
            {
                CommonExtend.ErrorLog(validEx, "数据验证异常");
                Response.Redirect(str500Page, true);
            }
            catch (Exception ex)
            {
                CommonExtend.ErrorLog(ex, "BasePage的OnLoad方法报错");
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// 获得页面不带扩展名的名称
        /// </summary>
        /// <returns></returns>
        protected string GetPhysicalFileNameWithoutExt()
        {
            var phyPath = Request.PhysicalPath;
            string strRet = string.Empty;
            if (phyPath.LastIndexOf("\\") > -1)
            {
                strRet = phyPath.Substring(phyPath.LastIndexOf("\\") + 1);
                strRet = strRet.Substring(0, strRet.LastIndexOf("."));
            }
            else
            {
                throw new PageLoadException("未能正常获取访问页面名称");
            }
            return strRet;
        }

        //protected override void OnPreRender(EventArgs e)
        //{
        //    base.OnPreRender(e);
        //}

        /// <summary>
        /// 退出登录方法
        /// </summary>
        protected virtual void Quit()
        {
            if (Session[SessionKey.UserInfo] != null)
            {
                Session.Clear();
                Response.Redirect(strLoginUrl, true);
            }
            else//session和cookie都丢失，相当于已经退出了，只需要跳转到登录页面即可
            {
                Response.Redirect(strLoginUrl, true);
            }
        }
    }
}